package com.bruip.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.SessionScope;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 王若龙
 * @CreateTime 2022-09-05 17:29
 *
 * 向域对象共享数据
 * 1.通过ModelAndView向请求域共享数据
 * 使用ModelAndView时，可以使用其Model功能向请求域共享数据
 * 使用View功能设置逻辑视图，但是控制器方法一定要将ModelAndView作为方法的返回值
 * 2.使用Model向请求域共享数据
 * 3.使用Map向请求域共享数据
 * 4.使用ModelMap向请求域共享数据
 *
 * Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
 */
@Controller
@RequestMapping("/scope")
public class TestScopeController {

    @RequestMapping("/mav")
    public ModelAndView mav(){
        /*
            ModelAndView 包含 model 和view 的功能
            model:向请求域共享数据
            view：设置逻辑视图实现页面跳转
         */
        ModelAndView modelAndView = new ModelAndView();
        //向请求域共享数据
        modelAndView.addObject("testRequestScope", "hello testRequestScope");
        //设置逻辑视图
        modelAndView.setViewName("success");
        return modelAndView;
    }

    @RequestMapping("model")
    public String model(Model model){
        model.addAttribute("testRequestScope", "hello Model");
        return "success";
    }

    @RequestMapping("/map")
    public String map(Map<String, Object> map){
        map.put("testRequestScope", "hello Map");
        return "success";
    }

    @RequestMapping("model/map")
    public String modelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope", "hello modelMap");
        return "success";
    }


    @RequestMapping("/session")
    public String session(HttpSession httpSession){
        httpSession.setAttribute("testRequestScope", "hello session");
        return "success";
    }
    @RequestMapping("/application")
    public String application(HttpSession session){
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("testRequestScope", "hello application");
        return "success";
    }

}
